from typing import Dict, Any
import numpy as np

try:
    from gglobal import logger
except ImportError:
    import logging
    logger = logging.getLogger(__name__)

def process_scan_reverse(msg_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    处理激光扫描数据反转
    由于激光是倒装的，需要将ranges和intensities数组进行反转
    
    Args:
        msg_dict: 原始激光扫描消息字典
        
    Returns:
        反转后的激光扫描消息字典
    """
    try:
        # 复制原始消息
        reversed_msg = msg_dict.copy()
        
        # 反转ranges数组
        if 'ranges' in msg_dict:
            if isinstance(msg_dict['ranges'], list):
                # 转换为numpy数组并反转
                reversed_msg['ranges'] = np.array(list(reversed(msg_dict['ranges'])), dtype=np.float32)
                logger.debug(f"反转ranges数组，长度: {len(msg_dict['ranges'])}")
            elif hasattr(msg_dict['ranges'], 'dtype'):  # 已经是numpy数组
                reversed_msg['ranges'] = np.flip(msg_dict['ranges'])
                logger.debug(f"反转ranges数组（numpy），长度: {len(msg_dict['ranges'])}")
        
        # 反转intensities数组
        if 'intensities' in msg_dict:
            if isinstance(msg_dict['intensities'], list):
                # 转换为numpy数组并反转
                reversed_msg['intensities'] = np.array(list(reversed(msg_dict['intensities'])), dtype=np.float32)
                logger.debug(f"反转intensities数组，长度: {len(msg_dict['intensities'])}")
            elif hasattr(msg_dict['intensities'], 'dtype'):  # 已经是numpy数组
                reversed_msg['intensities'] = np.flip(msg_dict['intensities'])
                logger.debug(f"反转intensities数组（numpy），长度: {len(msg_dict['intensities'])}")
        
        return reversed_msg
        
    except Exception as e:
        logger.error(f"处理激光扫描数据反转时出错: {e}", exc_info=True)
        return msg_dict  # 出错时返回原始数据

def process_scan_down_right_reverse(msg_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    处理/scan_down_right话题的激光扫描数据反转
    """
    return process_scan_reverse(msg_dict)

def process_scan_down_left_reverse(msg_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    处理/scan_down_left话题的激光扫描数据反转
    """
    return process_scan_reverse(msg_dict)

def process_scan_init_down_reverse(msg_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    处理/scan_init_down话题的激光扫描数据反转
    """
    return process_scan_reverse(msg_dict)